const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
let isDev = process.env.NODE_ENV === 'development'
const VueLoaderPlugin = require('vue-loader/lib/plugin')
var path = require('path')
var webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin') // 复制静态资源的插件
const CleanWebpackPlugin = require('clean-webpack-plugin') // 清空打包目录的插件
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const CompressionWebpackPlugin = require('compression-webpack-plugin')

function resolve(pathStr) {
  return path.resolve(__dirname, pathStr)
}

let config = {
  mode: isDev ? 'development' : 'production',
  entry: {
    main: './src/index.js'
  },
  devtool: isDev ? 'source-map' : false,
  devServer: {
    hot: true,
    // inline: true,//DevServer 会在构建完变化后的代码时通过代理客户端控制网页刷新。
    port: 3241,
    host: '0.0.0.0',
    open: 'http://localhost:' + 3241 + '/'
  },
  output: {
    path: __dirname + '/dist',
    filename: './static/js/[name].js'
  },
  resolve: {
    modules: [
      resolve('src'),
      resolve('static'),
      resolve('node_modules')
    ],
    extensions: ['.js', '.jsx', '.ts', '.vue'],
    alias: {}
  
  },
  optimization: {
    minimizer: [
      new OptimizeCSSAssetsPlugin({}),
      new UglifyJsPlugin({
        uglifyOptions: {
          comments: false,  //去掉注释
          mangle: {
            safari10: true
          },
          compress: {
            warnings: false, // 在UglifyJs删除没有用到的代码时不输出警告
            drop_console: true, // 删除所有的 `console` 语句，可以兼容ie浏览器
            collapse_vars: true, // 内嵌定义了但是只用到一次的变量
            reduce_vars: true, // 提取出出现多次但是没有定义成变量去引用的静态值
            drop_debugger: true
        
          }
      
        },
        cache: true,
        parallel: true
      })
    ],
    splitChunks: {
      chunks: 'async',
      minSize: 30000,
      // maxSize:40000,
      minChunks: 1,
      maxAsyncRequests: 5,
      maxInitialRequests: 3,
      name: false
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /.(t|j)s(x)?$/,
        include: resolve('src'),
        use: [
  
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              'presets': [
                // 把es6转成es5
                ['env', {'modules': false}],
                'stage-0'
              ],
              // 把装饰器语法转成es5
              'plugins': ['transform-decorators-legacy', 'transform-runtime'],
              'env': {
                'development': {
                  'plugins': ['dynamic-import-node']
                }
              }
            }
          },
          {
            loader: 'ts-loader',
            options: {
              transpileOnly: true //HMR doesn't work without this
            }
          }
        ]
      },
      {
        test: /.s?css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              publicPath: '../../'
            }
          },
          {
            loader: 'css-loader',
            options: {
              // modules: true,
              // localIdentName: isDev ? '[local]' : '[hash:base64:5]',
              // camelCase: true,
              sourceMap: true
            }
          }, {
            loader: 'postcss-loader',
            options: {
              ident: 'postcss',
              sourceMap: true,
              plugins: [
                require('autoprefixer')({
                  browsers: ['last 10 versions']
                })
                //postcss-pxtorem
              ]
            }
          }, {
            loader: 'sass-loader',
            options: {
              sourceMap: true
            }
          }
        ]
  
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: ('static/img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: ('static/media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: ('static/fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
    ...(isDev ? [
        new webpack.HotModuleReplacementPlugin()
      ] :
      [
        // new BundleAnalyzerPlugin(),
        new CleanWebpackPlugin([path.join(__dirname, 'dist')]),
        new CopyWebpackPlugin([
          {
            from: path.resolve(__dirname, 'static'),
            to: path.resolve(__dirname, 'dist/static'),
            ignore: ['.*']
          }
        ]),
        // gzip
        new CompressionWebpackPlugin({
          // asset: '[path].gz[query]',  2 版本已被删除
          algorithm: 'gzip',
          test: new RegExp(
            '\\.(' + (['js', 'css']).join('|') + ')$'
          ),
          cache: true,
          threshold: 10240,
          minRatio: 0.8
        })
      
      ]),
    new HtmlWebpackPlugin({
      template: resolve('src/index.html'),
      favicon: resolve('src/favicon.ico'),
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
      },
      chunksSortMode: 'dependency'
    }),
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash:8].css',
      chunkFilename: '[contenthash:8].css'
    })
  
  
  ]
}

module.exports = () => {
  console.log(config.mode)
  return config
}

